iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 4
0
自我挑戰組

各種筆記系列 第 4

[Kata] Clojure - Day 4

  • 分享至 

  • xImage
  •  

Alternate case

Write function alternateCase which switch every letter in string from upper to lower and from lower to upper. E.g: Hello World -> hELLO wORLD
把字串中的字母換成相反的大小寫字母

(ns kata.alternate-case-test
  (require [clojure.test :refer :all])
  (use [kata.alternate-case :rename {alternate-case solution}]))

(deftest sample-tests
  (is (= (solution "") ""))
  (is (= (solution "abc") "ABC"))
  (is (= (solution "Hello World!") "hELLO wORLD!"))
  (is (= (solution "CodeWars") "cODEwARS"))
  (is (= (solution "i LIKE MAKING KATAS VERY MUCH!") "I like making katas very much!"))
  (is (= (solution "0 gravity 0 calories!") "0 GRAVITY 0 CALORIES!")))

Solution

Each alphabet checked by isLowerCase or isUpeerCase and turned to opposite case by toUpperCase & toLowerCase. If other conditions happens (eg. space, punctuation marks) will return itself.

(ns kata.alternate-case)

(defn switch-case [a]
  (cond 
   (Character/isLowerCase a) (Character/toUpperCase a)
   (Character/isUpperCase a) (Character/toLowerCase a)
   :else a) 
  )

(defn solution [s]
  (apply str (map switch-case s))
  )

上一篇
[Kata] Clojure - Day 3
下一篇
[Kata] Clojure - Day 5
系列文
各種筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言